package com.bwie.system.service.impl;

import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.User;
import com.bwie.common.domain.UserGift;
import com.bwie.common.exception.BizException;
import com.bwie.common.utils.JwtUtils;
import com.bwie.system.mapper.UserGiftMapper;
import com.bwie.system.service.UserGiftService;
import io.netty.handler.codec.compression.Bzip2Decoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @className: UserGiftServiceImpl
 * @Description: TODO
 * @version: v1.８.0
 * @author:
 * @date:
 */
@Service
public class UserGiftServiceImpl implements UserGiftService {
    @Autowired
    private UserGiftMapper userGiftMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void addUserGift(List<UserGift> userGift) {
        //参数校验
        int size = userGift.size();
        if(size>2 ||size<0) {
            throw new BizException("已超过2件商品或空值报错");
        }

        //获取登录人信息
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        User user = (User) redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);

        //获取登录人领取记录
        List<UserGift> byUserId = userGiftMapper.findByUserId(user.getId());

        //根据记录条数，判断当前登录人还能领取多少礼品
        if(byUserId.size()>=2){
            throw new BizException("已兑换2件礼品");
        } else if (byUserId.size()==1) {//还能兑换一件
            UserGift userGift1 = byUserId.get(0);
            Integer giftId = userGift1.getGiftId();
            //判读是否重复兑换
            if(userGift.get(0).getUserId()==giftId){
                throw new BizException("每个礼物同一用户仅可兑换一次");
            }
            //添加记录
            userGiftMapper.addUserGiftBatch(user.getId(), userGift);
        } else if (byUserId.size() == 0) {//还能兑换2件
            //判断需要兑换的礼品是否重复
            if(userGift.get(0).getGiftId() == userGift.get(1).getUserId()){
                throw new BizException("每个礼物同一用户仅可兑换一次");
            }
            userGiftMapper.addUserGiftBatch(user.getId(), userGift);
        }
    }
}
